package com.hehanpeng.springbootnetty.handler.impl;

import com.hehanpeng.springbootnetty.annotation.Handler;
import com.hehanpeng.springbootnetty.busi.busiservice.BaseBusiService;
import com.hehanpeng.springbootnetty.busi.busiservice.SpringBusiServiceManager;
import com.hehanpeng.springbootnetty.java8583.core.Iso8583CibMessage;
import com.hehanpeng.springbootnetty.java8583.core.Iso8583MessageCibFactory;
import com.hehanpeng.springbootnetty.java8583.field.Iso8583Field;
import com.hehanpeng.springbootnetty.model.entity.MsgEntity;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import static com.hehanpeng.springbootnetty.constant.InstructionConst.SOCKET_CIB_PARSE_REQUEST;
import static com.hehanpeng.springbootnetty.constant.InstructionConst.SOCKET_CLOSE_RESPONSE;

/**
 * 关闭连接
 */
@Handler(instruction = SOCKET_CIB_PARSE_REQUEST)
public class CibParseHandler extends AbstractMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(CibParseHandler.class);

    @Resource
    private Iso8583MessageCibFactory iso8583MessageCibFactory;

    /**
     * 客户端要求关闭连接
     *
     * @param ctx     上下文
     * @param message 待处理的消息
     * @return 连接关闭响应
     */
    @Override
    public MsgEntity doDecoder(ChannelHandlerContext ctx, byte[] message) {
        //解析请求报文
        Iso8583CibMessage req = iso8583MessageCibFactory.parse(message);
        logger.info("server接收数据:{}", req.toFormatString());
        Iso8583Field value = req.getValue(3);
        String mti = req.getMti();
        BaseBusiService messageHandler = SpringBusiServiceManager.getMessageHandler(mti, value.getValue());
        try {
            MsgEntity resp = messageHandler.execute(req);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MsgEntity msgEntity = register(message);
            msgEntity.setInstruction(SOCKET_CLOSE_RESPONSE);
            msgEntity.setMsgBody(new byte[0]);
            return msgEntity;
        }
    }
}
